package cn.uexpo.lhz.common;

import cn.uexpo.lhz.biz.ManageEquipmentBiz;
import cn.uexpo.lhz.common.utils.GenerateToken;
import cn.uexpo.lhz.domain.ManageEquipment;
import cn.uexpo.lhz.domain.ManageEquipmentExample;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈MQTT接收消息处理〉
 *
 * @author lenovo
 * @create 2018/6/4
 * @since 1.0.0
 */

@Slf4j
@Configuration
@IntegrationComponentScan
public class MqttReceiveConfig {

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client.id}")
    private String clientId;

    @Value("${spring.mqtt.default.topic}")
    private String defaultTopic;

    @Value("${spring.mqtt.completionTimeout}")
    private int completionTimeout;   //连接超时


    @Autowired
    private ManageEquipmentBiz manageEquipmentBiz;


    @Autowired
    private GenerateToken generateToken;


    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        mqttConnectOptions.setKeepAliveInterval(2);  //设置心跳包发送间隔，单位：秒

        return mqttConnectOptions;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

    //接收通道
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    public String getHXX(){
        return "11111111111111111111111111";
    }

    @Bean
    public MessageProducer inbound() {
        String hxx = getHXX();
        System.out.println(hxx+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(clientId + "_inbound", mqttClientFactory(),
                        "one", "two", "three", "four", "staffMsg", "EventDependencyMsg", "equipmentState"
                        , "face_pad_state", "equipmentEdit", "staffUpdateImageMsg", "itemRules","staffState","idcComparison");
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(1);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }


    //通过通道获取数据
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        //String generateToken = getToken();
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
                String type = topic.substring(topic.lastIndexOf("/") + 1, topic.length());
                if ("one".equalsIgnoreCase(topic)) {//监听one主题
                    log.info("one==============," + message.getPayload().toString());
                } else if ("two".equalsIgnoreCase(topic)) {//监听two主题
                    log.info("two==============," + message.getPayload().toString());
                } else if ("three".equalsIgnoreCase(topic)) {//监听three主题
                    log.info("three==============," + message.getPayload().toString());
                } else if ("four".equalsIgnoreCase(topic)) {//监听four主题
                    log.info("four==============," + message.getPayload().toString());
                } else if ("staffMsg".equalsIgnoreCase(topic)) {//监听staffMsg主题
                    log.info("staffMsg==============" + message.getPayload().toString());
                } else if ("EventDependencyMsg".equalsIgnoreCase(topic)) {//监听EventDependencyMsg主题
                    log.info("EventDependencyMsg==============" + message.getPayload().toString());
                } else if ("equipmentState".equalsIgnoreCase(topic)) {//监听equipmentState主题
                    log.info("equipmentState==============" + message.getPayload().toString());
                } else if ("face_pad_state".equalsIgnoreCase(topic)) {//监听face_pad_state主题
//                    log.info("face_pad_state==============" + message.getPayload().toString());
                    String deviceId = null;
                    String str = message.getPayload().toString();
                    JSONObject jsonObject = JSON.parseObject(str);
                    String time = jsonObject.getString("time");
                    deviceId = jsonObject.getString("deviceId");
                    ManageEquipmentExample example = new ManageEquipmentExample();
                    ManageEquipmentExample.Criteria citeria = example.createCriteria();
                    citeria.andDeviceidEqualTo(deviceId);//具有唯一性
                    List<ManageEquipment> equipments = manageEquipmentBiz.selectByExample(example);
                    if (null != equipments && equipments.size() > 0) {
                        ManageEquipment equipment = equipments.get(0);
                        equipment.setExtstr3(time);
                        manageEquipmentBiz.updateByPrimaryKeySelective(equipment);
                       // log.info("sqltime:::::::::::::::::" + equipment.getExtstr3());
                    }
                } else if ("equipmentEdit".equalsIgnoreCase(topic)) {//监听equipmentEdit主题
                    log.info("equipmentEdit==============" + message.getPayload().toString());
                } else if ("staffUpdateImageMsg".equalsIgnoreCase(topic)) {//监听staffUpdateImageMsg主题
                    log.info("staffUpdateImageMsg==============" + message.getPayload().toString());
                } else if ("itemRules".equalsIgnoreCase(topic)) {//监听itemRules主题
                    log.info("itemRules==============" + message.getPayload().toString());
                }else if ("staffState".equalsIgnoreCase(topic)) {//监听staffState主题
                    log.info("staffState==============" + message.getPayload().toString());
                }else if ("idcComparison".equalsIgnoreCase(topic)) {//监听idcComparison主题
                    log.info("idcComparison==============" + message.getPayload().toString());
                }

            }
        };
    }

}

